package org.jeecg.modules.system.service.impl;

import java.util.Iterator;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.util.dingtalk.DingMessageUtils;
import org.jeecg.modules.message.entity.SysMessageTemplate;
import org.jeecg.modules.message.service.ISysMessageTemplateService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.IMyPickUpBillService;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.google.common.collect.Lists;

import io.finer.erp.jeecg.bas.entity.BasMaterial;
import io.finer.erp.jeecg.bas.entity.BasMaterialCategory;
import io.finer.erp.jeecg.bas.entity.ZrkOrderProcess;
import io.finer.erp.jeecg.bas.entity.ZrkPushSet;
import io.finer.erp.jeecg.bas.entity.ZrkQzOrder;
import io.finer.erp.jeecg.bas.entity.ZzShoporder;
import io.finer.erp.jeecg.bas.service.IBasMaterialCategoryService;
import io.finer.erp.jeecg.bas.service.IBasMaterialService;
import io.finer.erp.jeecg.bas.service.IZrkOrderProcessService;
import io.finer.erp.jeecg.bas.service.IZrkPushSetService;
import io.finer.erp.jeecg.bas.service.IZrkQzOrderService;
import io.finer.erp.jeecg.bas.service.IZzShoporderService;
import io.finer.erp.jeecg.stock.entity.StkPickUpBill;
import io.finer.erp.jeecg.stock.entity.StkPickUpEntry;
import io.finer.erp.jeecg.stock.service.IStkPickUpBillService;
import io.finer.erp.jeecg.stock.service.IStkPickUpEntryService;

@Service
public class MyPickUpBillServiceImpl implements IMyPickUpBillService {
	@Autowired
	private IStkPickUpBillService stkPickUpBillService;
	@Autowired
	private ISysMessageTemplateService msgTemService;
	@Autowired
	private IZrkPushSetService pushSetService;
	@Autowired
	private ISysUserService sysUserService;
	@Autowired
	private ISysBaseAPI sysBaseApi;
	@Autowired
	private IZrkOrderProcessService processService;
	@Autowired
	private IZzShoporderService zzShoporderService;
	@Autowired
	private IStkPickUpEntryService pickUpEntryService;
	@Autowired
	private IBasMaterialCategoryService categoryService;
	@Autowired
	private IZrkQzOrderService zrkQzOrderService;
	@Autowired
	private IBasMaterialService materialService;

	/**
	 * @Description: 发送消息
	 * @param ids
	 * @return
	 * Create at: 2020-12-08 15:39:26
	 * @author: duany
	 * Revision:
	 *    2020-12-08 15:39:26 - first revision by duany
	 *        
	 */
	@Override
	public Result<?> sendMessage(String ids) {
		//保存完成后向有关人员发送消息。
    	StkPickUpBill pickUpBill = stkPickUpBillService.getById(ids);
    	//如果没有推送消息，则进行推送
    	if(pickUpBill != null && pickUpBill.getIsPush() != null && pickUpBill.getIsPush() == 0) {
    		//您有新的提货单等待提货，编号为：${id}, 批号为：${orderNo},工序编号为：${processNo},明细为：${info},请尽快登录后台管理系统进行提货单出库！
    		//取出消息模板
    		List<SysMessageTemplate> selectByCode = msgTemService.selectByCode("zrk_new_thd");
    		String mesId = pickUpBill.getMesId();
    		ZrkQzOrder qzOrder = this.zrkQzOrderService.getById(mesId);
    		if(null == qzOrder) {
    			return Result.error("未找到mes单");
    		}
    		String mesCode = qzOrder.getCode();
    		if(null != selectByCode && 0 < selectByCode.size()) {
    			SysMessageTemplate template = selectByCode.get(0);
    			String id = template.getId();
    			List<ZrkPushSet> pushSetList = pushSetService.selectByMessageTemplateId(id);
    			if(null != pushSetList && 0 != pushSetList.size()) {
    				Iterator<ZrkPushSet> iterator = pushSetList.iterator();
    				String message = template.getTemplateContent();
    				message = message.replace("${id}", pickUpBill.getBillNo());
    				message = message.replace("${processNo}", mesCode);
    				List<StkPickUpEntry> list = pickUpEntryService.selectByMainId(pickUpBill.getId());
    				if(null == list || 0 == list.size()) {
    					return Result.error("未找到提货单明细");
    				}
    				Iterator<StkPickUpEntry> it = list.iterator();
    				String info = "[";
    				List<BasMaterial> materialList = Lists.newArrayList();
    				while(it.hasNext()) {
    					StkPickUpEntry entry = it.next();
    					String materialId = entry.getMaterialId();
    					if(StringUtils.isNotBlank(materialId)) {
    						BasMaterial material = materialService.getById(materialId);
    						materialList.add(material);
    						continue;
    					}
    					info += "(";
    					
    					String categoryId = entry.getMaterialId();
    					if(StringUtils.isBlank(categoryId)){
    						categoryId=entry.getCategoryId();
						}
    					BasMaterialCategory category = categoryService.getById(categoryId);
    					String name = category.getName();
    					info += "物料：" + name + ",";
    					info += "物料编码：" + category.getCode() + ",";
    					info += "规格：" + entry.getModel() + ",";
    					info += "数量：" + entry.getNumber() + ",";
    					info += "备注：" + entry.getRemark() + ",";
    					info += ")";
    				}
    				info += "]";
    				message = message.replace("${info}", info);
    				while(iterator.hasNext()) {
    					//查询仓库的管理员和操作员


    					ZrkPushSet set = iterator.next();
    					//查询提醒人钉钉ID
    					String userId = set.getUserId();
						SysUser sysUser = sysUserService.getById("4fd5ddb6484f405399242de50540a61e");
						if(null == sysUser) {
							continue;
						}
						if(StringUtils.isBlank(sysUser.getThirdId())) {
							continue;
						}
						boolean flag=DingMessageUtils.sendDingMessage(sysUser.getThirdId(), message);
						if(flag) {
							//发送消息成功后,将该任务单状态设置为已推送,防止多次推送（统一消息发送多次在钉钉接口处理的时候会提示143106，该错误码代表发送消息重复，143105:表示企业自建应用每日推送给用户的消息超过上限
				    		pickUpBill.setIsPush(1);
				    		this.stkPickUpBillService.updateById(pickUpBill);
							//发送系统消息
							sysBaseApi.sendSysAnnouncement("admin", sysUser.getUsername(),template.getTemplateName(), message);
							return Result.ok();
						}
    				}
    			} else {
    				return Result.error("未找到相关人员");
    			}
    		} else {
    			return Result.error("没找到消息模板");
    		}
    	} else {
    		if(pickUpBill == null) {
    			return Result.error("没找到提货单");
    		} else {
    			return Result.error("消息已经发送");
    		}
    		
    	}
    	return Result.error("未知错误");
	}
	
	
}
